use crate::knowledge_graph::{KnowledgeGraph, Relation};
use crate::reasoning_chain::ReasoningChain;
use std::collections::HashMap;
use rand::Rng;

/// 自主学习器 - 主动从外部数据源学习
pub struct AutonomousLearner {
    reasoning_chain: ReasoningChain,
    learning_strategy: LearningStrategy,
    learning_history: Vec<LearningSession>,
    mastery_level: HashMap<String, f64>, // 概念 -> 掌握程度 (0-1)
}

/// 学习策略
#[derive(Debug, Clone)]
pub enum LearningStrategy {
    Sequential,      // 顺序学习
    RandomSampling,  // 随机采样
    Prioritized,     // 优先学习难度高的
    Curiosity,       // 好奇心驱动（优先学习相关概念）
}

/// 学习会话记录
#[derive(Debug, Clone)]
pub struct LearningSession {
    pub timestamp: std::time::SystemTime,
    pub concepts_learned: usize,
    pub relations_discovered: usize,
    pub confidence: f64,
}

impl AutonomousLearner {
    pub fn new() -> Self {
        let kg = KnowledgeGraph::new();
        let reasoning_chain = ReasoningChain::new(kg);

        AutonomousLearner {
            reasoning_chain,
            learning_strategy: LearningStrategy::Curiosity,
            learning_history: Vec::new(),
            mastery_level: HashMap::new(),
        }
    }

    /// 从新华词典数据自主学习
    pub fn learn_from_dictionary(&mut self, dictionary_data: &DictionaryData) {
        println!("\n🎓 开始自主学习新华词典...");
        println!("词典规模: {} 条词条\n", dictionary_data.entries.len());

        let mut learned_count = 0;
        let mut relations_count = 0;

        for (i, entry) in dictionary_data.entries.iter().enumerate() {
            // 显示学习进度
            if (i + 1) % 100 == 0 {
                println!("📖 已学习: {}/{} 词条", i + 1, dictionary_data.entries.len());
            }

            // 学习这个词条
            let result = self.learn_entry(entry);
            learned_count += result.concepts_learned;
            relations_count += result.relations_discovered;

            // 定期进行自我反思
            if (i + 1) % 500 == 0 {
                println!("\n🤔 进行自我反思...");
                self.self_reflect();
            }
        }

        // 记录学习会话
        let session = LearningSession {
            timestamp: std::time::SystemTime::now(),
            concepts_learned: learned_count,
            relations_discovered: relations_count,
            confidence: 0.8,
        };
        self.learning_history.push(session);

        println!("\n✅ 学习完成！");
        println!("  • 学到概念: {}", learned_count);
        println!("  • 发现关系: {}", relations_count);
        println!("  • 知识图谱大小: {}", self.reasoning_chain.knowledge_graph().get_stats());
    }

    /// 学习单个词条
    fn learn_entry(&mut self, entry: &DictionaryEntry) -> LearningResult {
        let mut result = LearningResult {
            concepts_learned: 0,
            relations_discovered: 0,
        };

        // 1. 学习词语本身
        self.reasoning_chain.knowledge_graph_mut().add_concept(
            &entry.word,
            &entry.definition,
            "新华词典",
        );
        result.concepts_learned += 1;

        // 2. 分析定义，提取关系
        result.relations_discovered += self.extract_relations_from_definition(
            &entry.word,
            &entry.definition,
        );

        // 3. 学习例句（如果有）
        for example in &entry.examples {
            self.learn_from_example(&entry.word, example);
        }

        // 4. 学习同义词和反义词
        for synonym in &entry.synonyms {
            self.reasoning_chain.knowledge_graph_mut().add_relation(
                Relation::Similar(entry.word.clone(), synonym.clone()),
            );
            result.relations_discovered += 1;
        }

        for antonym in &entry.antonyms {
            self.reasoning_chain.knowledge_graph_mut().add_relation(
                Relation::Opposite(entry.word.clone(), antonym.clone()),
            );
            result.relations_discovered += 1;
        }

        // 5. 更新掌握程度
        self.mastery_level.insert(entry.word.clone(), 0.6);

        result
    }

    /// 从定义中提取关系
    fn extract_relations_from_definition(&mut self, word: &str, definition: &str) -> usize {
        let mut count = 0;
        let kg = self.reasoning_chain.knowledge_graph_mut();

        // 模式1: "X是Y的一种"
        if definition.contains("的一种") {
            if let Some(start) = definition.find("是") {
                if let Some(end) = definition[start..].find("的一种") {
                    let category = &definition[start+3..start+end].trim();
                    if !category.is_empty() {
                        kg.add_relation(Relation::IsA(word.to_string(), category.to_string()));
                        count += 1;
                    }
                }
            }
        }

        // 模式2: "指..."
        if definition.starts_with("指") {
            let desc = definition[3..].trim();
            if !desc.is_empty() {
                kg.add_concept(word, desc, "定义提取");
            }
        }

        // 模式3: "X属于Y"
        if definition.contains("属于") {
            let parts: Vec<&str> = definition.split("属于").collect();
            if parts.len() >= 2 {
                let category = parts[1].split(&['，', '。', '；'][..]).next().unwrap_or("").trim();
                if !category.is_empty() {
                    kg.add_relation(Relation::IsA(word.to_string(), category.to_string()));
                    count += 1;
                }
            }
        }

        // 模式4: "用于..."
        if definition.contains("用于") || definition.contains("用来") {
            kg.add_relation(Relation::CanDo(
                word.to_string(),
                definition.to_string(),
            ));
            count += 1;
        }

        // 模式5: "具有...特征"
        if definition.contains("具有") || definition.contains("特点是") {
            kg.add_relation(Relation::HasProperty(
                word.to_string(),
                definition.to_string(),
            ));
            count += 1;
        }

        count
    }

    /// 从例句中学习
    fn learn_from_example(&mut self, word: &str, example: &str) {
        // 简单记录：将例句与词语关联
        // 实际应用中可以做更深入的句法分析
        if example.len() > 10 {
            self.reasoning_chain.knowledge_graph_mut().add_concept(
                &format!("{}_用法", word),
                example,
                "例句",
            );
        }
    }

    /// 自我反思和推理
    fn self_reflect(&mut self) {
        // 基于已有知识推理新知识
        let inferences = self.reasoning_chain.knowledge_graph_mut().infer_new_knowledge();
        
        if !inferences.is_empty() {
            println!("  💡 通过推理发现:");
            for (i, inference) in inferences.iter().take(3).enumerate() {
                println!("    {}. {}", i + 1, inference);
            }
        }
    }

    /// 自我测试 - 验证学到的知识
    pub fn self_test(&mut self, sample_size: usize) -> TestResult {
        println!("\n📝 进行自我测试...");
        
        let concepts: Vec<String> = self.mastery_level.keys().cloned().collect();
        if concepts.is_empty() {
            return TestResult {
                total: 0,
                correct: 0,
                accuracy: 0.0,
            };
        }

        let mut rng = rand::thread_rng();
        let mut correct = 0;
        let test_count = sample_size.min(concepts.len());

        for _ in 0..test_count {
            let idx = rng.gen_range(0..concepts.len());
            let concept = &concepts[idx];

            // 测试：能否回忆起这个概念的定义
            if self.reasoning_chain.knowledge_graph().has_concept(concept) {
                correct += 1;
            }
        }

        let accuracy = correct as f64 / test_count as f64;
        
        println!("  测试结果: {}/{} 正确", correct, test_count);
        println!("  准确率: {:.2}%", accuracy * 100.0);

        TestResult {
            total: test_count,
            correct,
            accuracy,
        }
    }

    /// 主动探索 - 基于好奇心学习相关概念
    pub fn active_exploration(&mut self, start_concept: &str, depth: usize) {
        println!("\n🔍 主动探索相关概念...");
        println!("起点: {}", start_concept);

        let mut explored = std::collections::HashSet::new();
        let mut to_explore = vec![(start_concept.to_string(), 0)];

        while let Some((concept, current_depth)) = to_explore.pop() {
            if current_depth >= depth || explored.contains(&concept) {
                continue;
            }

            explored.insert(concept.clone());
            println!("  深度{}: 探索 '{}'", current_depth, concept);

            // 查找相关概念
            let related = self.reasoning_chain.knowledge_graph().find_related(&concept);
            
            for rel in related {
                if !explored.contains(&rel) {
                    to_explore.push((rel, current_depth + 1));
                }
            }
        }

        println!("  共探索 {} 个相关概念", explored.len());
    }

    /// 获取学习统计
    pub fn get_statistics(&self) -> LearningStatistics {
        LearningStatistics {
            total_sessions: self.learning_history.len(),
            total_concepts: self.mastery_level.len(),
            average_mastery: if self.mastery_level.is_empty() {
                0.0
            } else {
                self.mastery_level.values().sum::<f64>() / self.mastery_level.len() as f64
            },
        }
    }

    /// 导出知识
    pub fn export_knowledge(&self) -> Vec<String> {
        self.reasoning_chain.knowledge_graph().export_knowledge()
    }

    /// 获取推理链引用
    pub fn reasoning_chain(&self) -> &ReasoningChain {
        &self.reasoning_chain
    }

    /// 获取推理链的可变引用
    pub fn reasoning_chain_mut(&mut self) -> &mut ReasoningChain {
        &mut self.reasoning_chain
    }
}

impl Default for AutonomousLearner {
    fn default() -> Self {
        Self::new()
    }
}

/// 词典数据结构
#[derive(Debug, Clone)]
pub struct DictionaryData {
    pub entries: Vec<DictionaryEntry>,
}

/// 词典词条
#[derive(Debug, Clone)]
pub struct DictionaryEntry {
    pub word: String,
    pub definition: String,
    pub examples: Vec<String>,
    pub synonyms: Vec<String>,
    pub antonyms: Vec<String>,
}

impl DictionaryData {
    pub fn new() -> Self {
        DictionaryData {
            entries: Vec::new(),
        }
    }

    /// 从文件加载（简化版）
    pub fn load_from_file(path: &str) -> std::io::Result<Self> {
        use std::fs::File;
        use std::io::{BufRead, BufReader};

        let file = File::open(path)?;
        let reader = BufReader::new(file);
        let mut data = Self::new();
        
        let mut current_entry: Option<DictionaryEntry> = None;

        for line in reader.lines() {
            let line = line?;
            let line = line.trim();

            if line.is_empty() {
                if let Some(entry) = current_entry.take() {
                    data.entries.push(entry);
                }
                continue;
            }

            // 解析格式：词语|定义|例句|同义词|反义词
            let parts: Vec<&str> = line.split('|').collect();
            if parts.len() >= 2 {
                let entry = DictionaryEntry {
                    word: parts[0].trim().to_string(),
                    definition: parts[1].trim().to_string(),
                    examples: if parts.len() > 2 {
                        parts[2].split(';').map(|s| s.trim().to_string()).collect()
                    } else {
                        Vec::new()
                    },
                    synonyms: if parts.len() > 3 {
                        parts[3].split(';').map(|s| s.trim().to_string()).collect()
                    } else {
                        Vec::new()
                    },
                    antonyms: if parts.len() > 4 {
                        parts[4].split(';').map(|s| s.trim().to_string()).collect()
                    } else {
                        Vec::new()
                    },
                };
                data.entries.push(entry);
            }
        }

        Ok(data)
    }

    /// 创建示例词典数据
    pub fn create_sample() -> Self {
        let mut data = Self::new();

        // 添加示例词条
        let entries = vec![
            ("人工智能", "研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门新的技术科学", "人工智能在医疗领域有广泛应用", "AI;智能系统", ""),
            ("机器学习", "人工智能的一个分支，指机器通过算法从数据中自动学习和改进的能力", "机器学习可以用于图像识别", "自动学习", ""),
            ("深度学习", "机器学习的一种方法，使用多层神经网络进行学习", "深度学习推动了AI的发展", "", ""),
            ("神经网络", "一种模拟人脑神经元网络的计算模型", "神经网络可以处理复杂的模式识别任务", "人工神经网络", ""),
            ("算法", "解决问题的步骤和方法的精确描述", "排序算法有很多种", "方法;步骤", ""),
            ("数据", "用于记录信息的符号或数字", "大数据分析很重要", "信息", ""),
            ("学习", "通过经验获得知识或技能的过程", "学习是终身的事业", "求学;进修", ""),
            ("推理", "从已知信息推导出新结论的思维过程", "逻辑推理能力很重要", "推断;演绎", ""),
            ("知识", "人类认识客观世界的成果", "知识就是力量", "学问;学识", "无知"),
            ("智能", "获取和运用知识的能力", "人类拥有高度的智能", "聪慧;智慧", "愚笨"),
        ];

        for (word, definition, examples, synonyms, antonyms) in entries {
            data.entries.push(DictionaryEntry {
                word: word.to_string(),
                definition: definition.to_string(),
                examples: if examples.is_empty() {
                    Vec::new()
                } else {
                    vec![examples.to_string()]
                },
                synonyms: synonyms.split(';').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect(),
                antonyms: antonyms.split(';').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect(),
            });
        }

        data
    }
}

impl Default for DictionaryData {
    fn default() -> Self {
        Self::new()
    }
}

/// 学习结果
struct LearningResult {
    concepts_learned: usize,
    relations_discovered: usize,
}

/// 测试结果
pub struct TestResult {
    pub total: usize,
    pub correct: usize,
    pub accuracy: f64,
}

/// 学习统计
pub struct LearningStatistics {
    pub total_sessions: usize,
    pub total_concepts: usize,
    pub average_mastery: f64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_autonomous_learner() {
        let mut learner = AutonomousLearner::new();
        let dictionary = DictionaryData::create_sample();
        
        learner.learn_from_dictionary(&dictionary);
        
        let stats = learner.get_statistics();
        assert!(stats.total_concepts > 0);
    }

    #[test]
    fn test_dictionary_data() {
        let data = DictionaryData::create_sample();
        assert!(!data.entries.is_empty());
    }
}

